package com.earnings.okhttputils.utils.ui.activity.common;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.earnings.R;
import com.earnings.okhttputils.utils.OkHttp.OkHttpUtils;
import com.earnings.okhttputils.utils.OkHttp.utils.ToastUtils;
import com.earnings.okhttputils.utils.UrlConstant.Constant;
import com.earnings.okhttputils.utils.UrlConstant.HttpUrl;
import com.earnings.okhttputils.utils.bean.TurnRecordData;
import com.earnings.okhttputils.utils.god.GodLeftHandBaseActivity;
import com.earnings.okhttputils.utils.https.HttpArrayCallback;
import com.earnings.okhttputils.utils.https.HttpMap;
import com.earnings.okhttputils.utils.utils.CommonUtil;
import com.uuzuche.lib_zxing.activity.CaptureFragment;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.io.File;
import java.util.List;
import java.util.Map;


/**
 * Created by Administrator on 2016/9/1.
 *  调用摄像头扫描页面
 *
 */

public abstract class ScanActivity extends GodLeftHandBaseActivity implements View.OnClickListener {

    private static final int REQUEST_IMAGE =3 ;
    public static final int REQUEST_CAIBAO =9 ;
    private static final int MY_PERMISSIONS_REQUEST_CALL_CAMERA =1 ;
    private CaptureFragment captureFragment;
    private LinearLayout backLinearLayout;

    private ProgressDialog progressDialog;


    @Override
    protected int onCreateLayoutId() {
        return  R.layout.activity_scan;
    }

    @Override
    protected void init() {
        setHideTopView();
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            //如果没有授权，则请求授权
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CALL_CAMERA);
        }else{

        }
        captureFragment = new CaptureFragment();
        // 为二维码扫描界面设置定制化界面
        CodeUtils.setFragmentArgs(captureFragment, R.layout.scan_camera);
        captureFragment.setAnalyzeCallback(analyzeCallback);

        getSupportFragmentManager().beginTransaction().replace(R.id.fl_my_container,captureFragment).commit();
        setTitle("扫一扫");
        findViewById(R.id.album).setOnClickListener(this);
        findViewById(R.id.flash).setOnClickListener(this);
        findViewById(R.id.backscan).setOnClickListener(this);
    }



    boolean isopen=false;
    @Override
    public void onClick(View v) {

        int i = v.getId();
        if (i == R.id.album) {
            Intent intent = new Intent( Intent.ACTION_GET_CONTENT );
            intent.addCategory( Intent.CATEGORY_OPENABLE );
            intent.setType( "image/*" );
            startActivityForResult( intent, REQUEST_IMAGE );

        } else if (i == R.id.flash) {
            if (isopen) {
                CodeUtils.isLightEnable( false );
                isopen = false;
            } else {
                CodeUtils.isLightEnable( true );
                isopen = true;
            }

        } else if (i == R.id.backscan) {
            finish();

        }
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            if (data != null) {
                Uri uri = data.getData();
                ContentResolver cr = getContentResolver();
                try {
                    Bitmap mBitmap = MediaStore.Images.Media.getBitmap(cr, uri);//显得到bitmap图片

                    CodeUtils.analyzeBitmap(String.valueOf(mBitmap), new CodeUtils.AnalyzeCallback() {
                        @Override
                        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
                            Toast.makeText(getContext(), "解析结果:" + result, Toast.LENGTH_LONG).show();
                            handleCode(result);
                        }

                        @Override
                        public void onAnalyzeFailed() {
                            Toast.makeText(getContext(), "解析二维码失败", Toast.LENGTH_LONG).show();
                        }
                    });

                    if (mBitmap != null) {
                        mBitmap.recycle();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 二维码解析回调函数
     */
    CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {


        @Override
        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {

         //d   Toast.makeText(getContext(), "解析结果:" + result, Toast.LENGTH_LONG).show();
            handleCode(result);
        }

        @Override
        public void onAnalyzeFailed() {
            Toast.makeText(getContext(), "解析二维码失败", Toast.LENGTH_LONG).show();
        }
    };



    public void handleCode(String result){
        Log.e( Constant.TAG,result);
      //  ToastUtils.showToast( getContext(),result );
        bundleData.putString( "url",result );
        if(result.indexOf( "seller_id" )>-1){
            scanStore();

        }else  if(result.indexOf( "transfer" )>-1){
            String phone="";String price="";
            String url = bundleData.getString( "url" );
            String[] urls = url.split( "/" );
            if (urls.length > 0) {
                for (int i = 0; i < urls.length; i++) {
                    if (urls[i].equals( "transfer" )) phone = urls[i + 1];
                    if (urls[i].equals( "transferMoney" )) price = urls[i + 1];


                }
            }

            if(bundleData.containsKey( "type" )){
                bundleData.putString( "phone",phone );
                mIntent.putExtras( bundleData );
                setResult( REQUEST_CAIBAO ,mIntent);
                finish();
        }else
            loadDataForPhone(phone,  price);
        }else  if(result.indexOf( "Mobile/User/reg/parentid" )>-1){
            String phone="";String price="";
            String url = bundleData.getString( "url" );
            String[] urls = url.split( "/" );
            if (urls.length > 0) {
                for (int i = 0; i < urls.length; i++) {
                    if (urls[i].equals( "parentid" )) phone = urls[i + 1];
                   // if (urls[i].equals( "transferMoney" )) price = urls[i + 1];


                }
            }
            if(bundleData.containsKey( "type" )){
                bundleData.putString( "phone",phone );
                mIntent.putExtras( bundleData );
                setResult( REQUEST_CAIBAO ,mIntent);
                finish();
            }else
            scanUser(phone);
        }

    }


    public void loadDataForPhone(String phone, final String price) {
        if(phone.equals( CommonUtil.getUser().getPhone() )){
            ToastUtils.showToast( getContext(),"不能给自己转账" );
            return;
        }
        showProgress();
        Map map = new HttpMap( getContext() );
        map.put( "mobile" ,phone);
        OkHttpUtils.post().url( HttpUrl.USER_FIND_DATA_URL ).params( map ).build().execute( new HttpArrayCallback<TurnRecordData>( getContext() ) {
            @Override
            public void onSuccess(List<TurnRecordData> object, String msg) {
                if(object.size()!=0){
                    ;
                    bundleData.putString( "phone",object.get( 0 ).getMobile() );
                    bundleData.putString( "nickname",object.get( 0 ).getNickname() );
                    bundleData.putString( "head",object.get( 0 ).getHead_pic() );
                    bundleData.putString( "price",price );
                    finish();
                    skipActivity( TurnPriceActivity.class );
                } else {
                   ToastUtils.showToast( getContext(),"未查找到该用户" );

                }

                dismissProgress();
                //  datas = (ArrayList<RecommendFriendsListData>) object.getList();
              /*  datas = (ArrayList<RecommendFriendsListData>) object.getList();
                initData();*/
            }

            @Override
            public void onFail(int code, String msg) {

                dismissProgress();
                ToastUtils.showToast( getContext(), msg );
            }


        } );


    }

    public abstract  void scanUser(String user);
    public abstract  void scanStore();
}
